package com.netty.study;

import com.netty.study.dto.UserMessage;
import com.netty.study.handler.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClient {


    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup clientGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        final MessageServiceHandler messageServiceHandler = new MessageServiceHandler();
        bootstrap.group(clientGroup).localAddress(9094)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new ByteToStringDecoderHandler())
                                .addLast(new StringToByteEncoderHandler())
                                .addLast(new StringToMessageDecoderHandler())
                                .addLast(new MessageToStringEncoderHandler())
                                .addLast(messageServiceHandler);
                    }
                });

        ChannelFuture future = bootstrap.connect("127.0.0.1", 9080).sync();
//        future.channel().writeAndFlush("hello").sync();
        UserMessage userMessage = new UserMessage("客户端", "第2条消息");
        future.channel().writeAndFlush(userMessage);
        future.channel().closeFuture().sync();
    }
}